import jwt
import datetime
import time
import pytz

'''生成token组件'''
# jwt_outtime = 0.0001        #设置过期时间
jwt_outtime = 1        #设置过期时间
jwt_Issuer = "admin"     #设置签发人
jwt_key = "admin010"    #加密密钥
tz = pytz.timezone('Asia/Shanghai') #时区

#加密
def GenToken(username,level):
    dic = {
        'exp': datetime.datetime.now(tz=tz)+ datetime.timedelta(days=jwt_outtime),  # 过期时间
        'iat': datetime.datetime.now(tz=tz),                               #  开始时间
        'iss': jwt_Issuer,                                            # 签名
        'data': {  # 加密内容
            'username': username,
            'level': level,
        },
    }
    s = jwt.encode(dic, jwt_key, algorithm='HS256')  # 加密生成字符串
    return s

#解密
def ParseToekn(token):
    try:
        s = jwt.decode(token, jwt_key, issuer=jwt_Issuer, algorithms=['HS256'])  # 解密，校验签名
        current_milli_time = lambda: int(round(time.time() ))
        if current_milli_time() > s["exp"]:                             #时间验证 看看token过期了没有
            return "", "token已过期"
    except Exception as e:
        print(e)
        return "", "解密失败"
    return s, None


